package edu.tjut.tjutcommunity.Interceptor;


import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.TokenExpiredException;
import edu.tjut.tjutcommunity.entity.Message;
import edu.tjut.tjutcommunity.entity.User;
import edu.tjut.tjutcommunity.service.UserService;
import edu.tjut.tjutcommunity.utils.JWTUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class RootRequestInterceptor implements HandlerInterceptor {

    @Autowired
    UserService userService;
    private final static Logger logger = LoggerFactory.getLogger(RootRequestInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //已经获得token了
        String token = request.getHeader("token");
        //从token中获取用户信息，并且检测权限
        String sub = JWTUtils.validateToken(token);
        User user = userService.getUserByStuId(sub);
        if (1 == user.getLevel()) return true; //管理员
        else return checkOwner(); //或者是自己管理
    }

    private boolean checkOwner() {
        return true;
    }
}